﻿#pragma once
#include "ADFGlobal.h"
#include "AsGlobalData.h"
#include "AsMetaType.h"
#include "AsDbEntity.h"
#include "AsDefine.h"
#include "AsThread.h"
#include "AsDbOperator.h"
#include "AsWorkThread.h"

class ADF_EXPORT AsSqlUtil :public AsGlobalData
{
	Q_OBJECT
public:	
	AsSqlUtil();
	~AsSqlUtil();

	void setOperator(AsDbOperator* oper);
	void init();

	//插入数据
	QVariant addData(AsDbEntity* pEntity);
	//删除数据
	bool deleteData(AsDbEntity* pEntity);
	//修改数据
	bool updateData(AsDbEntity* pEntity);
	//直接执行语句
	bool execSql(QString sql);
	
	template<typename _TYPE>
	bool queryDataList(QList<_TYPE>& dataList, QString querySql) {
		if (!std::is_base_of<AsDbEntity, _TYPE>()) {
			return false;
		}
		if (!m_isInited)
		{
			return false;
		}

		QSqlQuery query = m_pOperator->operQuery(querySql);
		while (query.next())
		{
			_TYPE entity;
			QVariantMap dataMap;
			for (auto key : entity.toVariantMap().keys())
			{
				dataMap[key] = query.value(key);
			}
			entity.fromVariantMap(dataMap);
			dataList << entity;
		}
		return true;
	}

private:
	bool m_isInited;
	AsThread* m_pThread;
	AsDbOperator* m_pOperator;

};
AS_DECLARE_META_TYPE(AsSqlUtil)
